﻿using System.Threading;
using System.Windows.Input;

using ABCat.Shared.Properties;
using ABCat.UI.WPF.UI;

namespace ABCat.UI.WPF.Models
{
	public abstract class AsyncOperationViewModelBase
	{
		#region + Fields +

		protected CancellationTokenSource CancellationTokenSource;

		#endregion
		#region + Properties +

		public bool IsAsyncOperationExecuting
		{
			get { return CancellationTokenSource != null; }
		}

		protected StatusBarStateViewModel StatusBarStateModel		{get; set;}

		#endregion
		#region + Ctor +

		protected AsyncOperationViewModelBase([NotNull] StatusBarStateViewModel statusBarStateModel )
		{
			StatusBarStateModel = statusBarStateModel;
		}

		#endregion
		#region + Logic +

		public void CancelAsyncOperation()
		{
			var cts = CancellationTokenSource;
			if (cts != null) cts.Cancel();
		}

		protected void OnAsynOperationCompleted()
		{
			CancellationTokenSource = null;
			ReportProgressSmall(-1, 0, null);
			ReportProgressTotal(-1, 0, null);
			CommandManager.InvalidateRequerySuggested();
		}

		protected void ReportProgressSmall(int current, int total, string message)
		{
			StatusBarStateModel.ProgressBarSmallMinimum = 0;
			StatusBarStateModel.ProgressBarSmallMaximum = total;
			StatusBarStateModel.ProgressBarSmallMessage = message;
			StatusBarStateModel.ProgressBarSmallValue = current;
		}

		protected void ReportProgressTotal(int current, int total, string message)
		{
			StatusBarStateModel.ProgressBarTotalMinimum = 0;
			StatusBarStateModel.ProgressBarTotalMaximum = total;
			StatusBarStateModel.ProgressBarTotalMessage = message;
			StatusBarStateModel.ProgressBarTotalValue = current;
		}

		#endregion
	}
}